package org.fuxia.im.core.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

import com.alibaba.fastjson.JSON;

public final class ObjectUtil
{

	private static final Charset	DEFAULT	= Charset.forName("UTF-8");

	public static final byte[] getByteBySeri(Object obj) throws Exception
	{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = null;
		try
		{
			oos = new ObjectOutputStream(baos);
			oos.writeObject(obj);
		}
		catch (IOException e)
		{
			e.printStackTrace();
			throw new Exception("--convert failure--");
		}
		finally
		{
			baos.close();
			oos.close();
		}

		return baos.toByteArray();
	}

	/**
	 *  将对象转换成字节数组。这里是先将对象转换成JSON字符串之后，再将字符转换成字节数组得到的
	 * @param obj
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static final byte[] getByteByJson(Object obj) throws UnsupportedEncodingException
	{
		return MessageGZIP.compressToByte(JSON.toJSONString(obj));
	}

	public static final <T> T getObjectByJson(String jsonStr , Class<T> clazz) throws Exception
	{
		T obj = null;
		try
		{
			obj = JSON.parseObject(jsonStr, clazz);
		}
		catch (Exception e)
		{
			throw e;
		}

		return obj;
	}

	public static final <T> T getObjectFromByte(byte[] bytes , Class<T> clazz) throws Exception
	{
		return getObjectByJson(MessageGZIP.uncompressToString(bytes), clazz);
	}

	/**
	 * 
	 * <b>Title:</b>  getObject </br>
	 * <b>Description:</b>  将字节数组转换成指定的类型，请确认字节数组是通过该类型的实例得到的，否则转换将会出现错误 </br>
	 * @param bytes
	 * @param classes
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static final <T> T getObjectFromSeri(byte[] bytes , Class<T> classes) throws Exception
	{
		T result;
		//将流序列化成对象  
		ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
		ObjectInputStream ois = null;
		try
		{
			ois = new ObjectInputStream(bis);
			result = ((T) ois.readObject());
		}
		catch (IOException e)
		{
			e.printStackTrace();
			throw new Exception("byte convert to object error");
		}
		finally
		{
			bis.close();
			if (ois != null)
			{
				ois.close();
			}
		}

		return result;
	}

	public static final String getJsonStr(Object o)
	{
		if(o == null) {
			return "";
		}
		return JSON.toJSONString(o);
	}

	public static final <T> T getObjectByJsonStr(String jsonStr , Class<T> clazz)
	{
		return JSON.parseObject(jsonStr, clazz);
	}
}
